<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/7 0007
 * Time: 下午 2:20
 */

namespace app\admin\controller\shopmoney;


use app\admin\model\City;
use app\admin\model\TuanCode;
use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;

class Shoporder extends Backend
{
    /**
     * TuanOrder模型对象
     */
    protected $model = null;
    protected $order_type;
    protected $pay_type;
    protected $back_status;
    protected $searchFields = 'tuaninfo.title';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('TuanOrder');
        $this->order_type = [
            '1' => '团购',
            '2' => '买单',
            '4' => '现金支付',
        ];
        $this->pay_type = [
            '0' => '未支付',
            '1' => '余额支付',
            '2' => '支付宝',
            '3' => '微信支付',
            '4' => '现金支付',
        ];
        $this->back_status = [
            '-1' => '返回商家失败',
            '0' => '无需返现',
            '1' => '待领取',
            '2' => '会员已领取',
            '3' => '商家已领取',
        ];
    }

    /**
     * *店铺交易列表
     * @date 2017/12/11
     * @auhthor yanggang
     * @return string|\think\response\Json
     */
    public function index()
    {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $map['shop_id'] = 19;
            $map = [
                'pay_status' => ['eq',2],
            ];
            $total = $this->model
                ->with(['tuaninfo'])
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();


            $list = $this->model
                ->with([
                    'tuaninfo' => function($query){
                        $query->withField('tuan_id,title');
                    }
                ])
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $key=>$value){
                $list[$key]['original_price'] = number_format($value['total_price']/100,2,'.','');
                if($value['order_type'] == 1){
                    //判断是否有退券
                    if($value['refund_num']  && $value['refund_num'] < $value['num'] ){
                        //实付金额
                        $value['price'] = $value['price'] - $value['price'] * $value['refund_num'] /$value['num'];
                        //订单金额
                        $value['total_price'] = $value['total_price'] - $value['total_price'] * $value['refund_num']/$value['num'];
                    }
                    $list[$key]['discount'] =  number_format(($value['total_price']-$value['integral']*100-$value['price'])/100,2,'.','');//'￥ '.number_format($value['discount'],2,'.','');
                } elseif ($value['order_type'] == 2){
                    //减免金额
                    $list[$key]['coupon_price'] =  number_format(($value['total_price']-$value['price'])/100,2,'.','');
                    $list[$key]['discount'] = price_format(0.00);
                    //订单金额
                    $list[$key]['total_price'] = number_format(($value['price']+$value['subtract']),2,'.','');
                }
                if($value['tuan_type'] == 3){
                    $list[$key]['total_price'] = price_format($value['price']).' +'.$value['integral'].'分';
                }else{
                    $list[$key]['total_price'] = price_format($value['total_price']);
                }
                //实际收益
                if($value['order_type'] == 1){
                    $code_list = Db::name('tuan_code')->where(['order_id'=>$value['order_id'],'is_used'=>1,'status'=>1])->column('settlement_price');
                    if($code_list){
                        $list[$key]['real_earnings'] = (count($code_list)*$code_list[0])/100;
                    }else{
                        $list[$key]['real_earnings'] = 0;
                    }
                }else{
                    $list[$key]['real_earnings'] = $value['settlement_price']/100;
                }
                $list[$key]['order_type'] = $this->order_type[$value['order_type']];
                if($list[$key]['order_type'] == '现金支付') {
                    $list[$key]['pay_type'] = 4;
                }
                $list[$key]['pay_type'] = $this->pay_type[$value['pay_type']];
                $list[$key]['price'] = price_format($value['price']);
                $list[$key]['integral'] = number_format($value['integral'],2,'.','');
                $list[$key]['back_money'] = price_format($value['back_money']);
                $list[$key]['back_status'] = $this->back_status[$value['back_status']];
            }

//            foreach ($list as $key => $value) {
//                $list[$key]['user']['type'] = $this->user_type[$value['user']['type']];
//                $list[$key]['fees'] = price_format($value['fees']);
//            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     *店铺交易详情
     * @date 2017/12/11
     * @auhthor yanggang
     *
     */
    public function edit($ids = NULL)
    {
        $where = [
            'order_id' => $ids,
            'pay_status'=>2
        ];
        $row = $this->model
            ->with(['shop','user','selearnings'])
            ->where($where)
            ->find();

        $selearnings_fee = 0;
        if($row['selearnings']){//计算实际分润
            foreach ($row['selearnings'] as $value){
                $selearnings_ids[]= $value['selearningsID'];
            }
            $selearnings_fee = Db::name('attract')->where(['source'=>['in',$selearnings_ids]])->sum('fees');
            $selearnings_fee = number_format($selearnings_fee,2,'.','');

        }

        //查找商家的会员信息，商家的地区
        $user_id = $row['shop']['user_id'];
        $shop_user_info = (new User())->field('phone,account')->where(['userID'=>$user_id])->find();
        $province = $row['shop']['province_id'];
        $city = $row['shop']['city_id'];
        $area = $row['shop']['area_id'];
        $city_map = [
            'cityID'=>['in',$province.','.$city.','.$area]
        ];
        $local_name = (new City())->where($city_map)->column('name');
        $local_name = implode('-',$local_name);

        //计算当前税率
       /* $row['rate'] = number_format(($row['price'] - $row['settlement_price']-$row['back_money'])/$row['price'],2) * 100;*/
        $pay_type = $this->pay_type;
        if($row['order_type'] == 1){//团购
            $tuan_type = $row->tuan->getAttr('type');
            $row['order_type_text'] = $tuan_type == 1 ? '团购套餐' : '代金券';
            //r如果退了券
            if($row['refund_num']  && $row['refund_num'] < $row['num'] ){
                $row['price'] = $row['price'] - $row['price'] * $row['refund_num'] /$row['num'];
                $row['total_price'] = $row['total_price'] - $row['total_price'] * $row['refund_num']/$row['num'];
            }
            //查询消费时间
            $used_time = (new TuanCode())->where(['order_id'=>$ids,'is_used'=>1])->max('used_time');
            $row['update_time'] = $used_time;
        }elseif ($row['order_type'] == 2){//买单
            $row['order_type_text'] = $row['total_price'] == $row['price'] ? '买单':'优惠买单';
        }elseif ($row['order_type'] == 4) {
            $row['order_type_text'] = $row['total_price'] == $row['price'] ? '买单' : '优惠买单';
        }
//        $row['order_type_text'] = $order_type[$row['order_type']];
        if($row['order_type'] == 4) {
            $row['pay_type_text'] = '现金支付';
            $row['add_integral'] = 0;
        } else {
            $row['pay_type_text'] = $pay_type[$row['pay_type']];
            $row['add_integral'] =  $row['order_status'] == 3 ? '+ '.intval($row['price']/100) : '未评价';
        }

        $row['coupon_price'] =  '￥ '.number_format(($row['total_price']-$row['integral']*100-$row['price'])/100,2,'.','');//'￥ '.number_format($value['discount'],2,'.','');

        if($row['discount'] == 0 ){
            $row['discount'] = 10;
        }
        //交易金额
        $row['price'] = price_format($row['price']+$row['subtract']);
        if ($row['not_preferential_price'] != 0) {
            $discount_price = ($row['total_price'] - $row['not_preferential_price'])* (1- $row['discount']/10) + $row['subtract'];
            $zk_price = ($row['total_price'] - $row['not_preferential_price']) * (1- $row['discount']/10);
        } else {
            $discount_price = $row['total_price'] * (1- $row['discount']/10) + $row['subtract'];
            $zk_price = $row['total_price'] * (1- $row['discount']/10);
        }
        $row['discount_text'] = $row['discount'].'折';
        //减免金额
        $row['discount'] = price_format($discount_price);
        //折扣立减
        $row['zk_price'] = price_format($zk_price);
        //随机立减
        $row['subtract'] = price_format($row['subtract']);
        //实付金额
        $row['actual_price'] = $row['price']-$row['subtract'];
        //原价
        $row['total_price'] = price_format($row['total_price']);
        $row['settlement_price'] = price_format($row['settlement_price']);
        $row['integral'] = '￥ '.number_format($row['integral'],2,'.','');
        $row['selearnings_fee'] = price_format($selearnings_fee);
        $row['back_money_text'] = price_format($row['back_money']);
        $row['back_status'] = $this->back_status[$row['back_status']];
        $row['shop']['local_name'] = $local_name;
        $row['shop']['user_info'] = $shop_user_info;
        if($row['shop']['discount'] == -1){
            $shop_dicount = '关闭';
        }elseif($row['shop']['discount'] == 0){
            $shop_dicount = '免单';
        }else{
            $shop_dicount = $row['shop']['discount'].'折';
        }
        $row['shop']['discount'] = $shop_dicount; //店铺首单优惠
//        return json($row);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}